﻿using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Threading.Tasks;

namespace BingWallpaperCore
{
    public class GetBingWallpaperService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private const string path = @"E:\每日壁纸";

        public GetBingWallpaperService(IHttpClientFactory httpClientFactory) => _httpClientFactory = httpClientFactory;


        [DllImport("user32.dll", EntryPoint = "SystemParametersInfo")]
        public static extern int SystemParametersInfo(
            int uAction,
            int uParam,
            string lpvParam,
            int fuWinIni
            );


        public async Task SetWallPaper()
        {
            var result = await GetImageJson();
            var savePath = await SaveImageFromWeb("http://cn.bing.com/" + result["url"], path, result["fullstartdate"]);
            SystemParametersInfo(20, 0, savePath, 0x2);
        }



        public async static Task<string> SaveImageFromWeb(string imgUrl, string path, string fileName)
        {
            if (string.IsNullOrWhiteSpace(path))
            {
                return string.Empty;
            }
            var imgName = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("/") + 1);
            var defaultType = ".jpg";
            var imgTypes = new string[] { ".jpg", ".jpeg", ".png", ".gif", ".bmp" };
            var imgType = imgUrl.ToString().Substring(imgUrl.ToString().LastIndexOf("."));
            foreach (string it in imgTypes)
            {
                if (imgType.ToLower() == (it))
                    break;
                if (it == (".bmp"))
                    imgType = defaultType;
            }

            var request = (HttpWebRequest)WebRequest.Create(imgUrl);
            request.UserAgent = "Mozilla/6.0 (MSIE 6.0; Windows NT 5.1; Natas.Robot)";
            request.Timeout = 3000;

            var response = await request.GetResponseAsync();
            var stream = response.GetResponseStream();

            if (response.ContentType.ToLower().StartsWith("image/"))
            {
                byte[] arrayByte = new byte[1024];
                int imgLong = (int)response.ContentLength;
                int l = 0;

                if (fileName == "")
                    fileName = imgName;
                var fso = new FileStream(path + "\\" + fileName + imgType, FileMode.Create);
                while (l < imgLong)
                {
                    int i = await stream.ReadAsync(arrayByte, 0, 1024);
                    await fso.WriteAsync(arrayByte, 0, i);
                    l += i;
                }

                fso.Dispose();
                stream.Dispose();
                response.Dispose();
                return path + "\\" + fileName + imgType;
            }
            else
            {
                return "";
            }
        }


        private async Task<Dictionary<string, string>> GetImageJson()
        {
            var client = _httpClientFactory.CreateClient();
            var response = await client.GetAsync("http://www.bing.com/HPImageArchive.aspx?w=1920&h=1080&format=js&idx=0&n=1&mkt=zh-CN");
            var content = await response.Content.ReadAsStringAsync();

            var Obj_JSON = JObject.Parse(content);

            var String_Images = Obj_JSON["images"][0].ToString();
            String_Images = String_Images.Remove(String_Images.Length - 16, 14);
            var Dic_Images = JsonConvert.DeserializeObject<Dictionary<string, string>>(String_Images);
            return Dic_Images;
        }
    }
}
